package com.foodcommunity.service.impl;

import com.foodcommunity.dto.DataAnalysisDTO;
import com.foodcommunity.mapper.DataAnalysisMapper;
import com.foodcommunity.mapper.FoodPostMapper;
import com.foodcommunity.mapper.RestaurantMapper;
import com.foodcommunity.service.DataAnalysisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 数据分析服务实现类
 */
@Service
public class DataAnalysisServiceImpl implements DataAnalysisService {

    @Autowired
    private DataAnalysisMapper dataAnalysisMapper;
    
    @Autowired
    private FoodPostMapper foodPostMapper;
    
    @Autowired
    private RestaurantMapper restaurantMapper;

    @Override
    public DataAnalysisDTO getOverallAnalysis() {
        DataAnalysisDTO analysisDTO = new DataAnalysisDTO();
        
        // 获取分类统计数据
        analysisDTO.setCategoryStats(dataAnalysisMapper.getCategoryStats());
        
        // 获取标签统计数据
        analysisDTO.setTagStats(dataAnalysisMapper.getTagStats());
        
        // 获取餐厅菜系统计数据
        analysisDTO.setCuisineTypeStats(dataAnalysisMapper.getCuisineTypeStats());
        
        // 获取用户活跃度统计数据
        analysisDTO.setUserActivityStats(dataAnalysisMapper.getUserActivityStats());
        
        // 获取评分分布统计数据
        analysisDTO.setRatingDistribution(dataAnalysisMapper.getRatingDistribution());
        
        // 获取月度趋势数据（默认12个月）
        analysisDTO.setMonthlyTrends(dataAnalysisMapper.getMonthlyTrends(12));
        
        return analysisDTO;
    }

    @Override
    public List<Map<String, Object>> getMonthlyTrends(int months) {
        return dataAnalysisMapper.getMonthlyTrends(months);
    }

    @Override
    public Map<String, Object> getUserPreferences(Long userId) {
        Map<String, Object> preferences = new HashMap<>();
        
        // 获取用户偏好分类
        preferences.put("preferredCategories", dataAnalysisMapper.getUserPreferredCategories(userId));
        
        // 获取用户偏好标签
        preferences.put("preferredTags", dataAnalysisMapper.getUserPreferredTags(userId));
        
        // 获取用户偏好餐厅菜系
        preferences.put("preferredCuisineTypes", dataAnalysisMapper.getUserPreferredCuisineTypes(userId));
        
        return preferences;
    }

    @Override
    public List<Map<String, Object>> getRecommendedPosts(Long userId, int limit) {
        // 基于用户偏好的分类和标签，推荐相关帖子
        List<Map<String, Object>> recommendedPosts = new ArrayList<>();
        
        // 获取用户偏好分类
        List<Map<String, Object>> preferredCategories = dataAnalysisMapper.getUserPreferredCategories(userId);
        
        // 获取用户偏好标签
        List<Map<String, Object>> preferredTags = dataAnalysisMapper.getUserPreferredTags(userId);
        
        // 如果用户有偏好分类，基于分类推荐
        if (preferredCategories != null && !preferredCategories.isEmpty()) {
            // 从偏好分类中获取前3个分类ID
            List<Long> categoryIds = new ArrayList<>();
            for (int i = 0; i < Math.min(3, preferredCategories.size()); i++) {
                categoryIds.add(Long.valueOf(preferredCategories.get(i).get("id").toString()));
            }
            
            // 基于分类ID获取推荐帖子
            if (!categoryIds.isEmpty()) {
                // 这里需要在FoodPostMapper中添加相应的方法
                // 实际项目中应该实现更复杂的推荐算法
                // 这里简化为根据分类和点赞数推荐
                recommendedPosts.addAll(foodPostMapper.selectRecommendedPostsByCategories(categoryIds, userId, limit));
            }
        }
        
        // 如果推荐数量不足，基于标签补充
        if (recommendedPosts.size() < limit && preferredTags != null && !preferredTags.isEmpty()) {
            // 从偏好标签中获取前5个标签ID
            List<Long> tagIds = new ArrayList<>();
            for (int i = 0; i < Math.min(5, preferredTags.size()); i++) {
                tagIds.add(Long.valueOf(preferredTags.get(i).get("id").toString()));
            }
            
            // 基于标签ID获取推荐帖子
            if (!tagIds.isEmpty()) {
                // 这里需要在FoodPostMapper中添加相应的方法
                List<Map<String, Object>> tagRecommendedPosts = foodPostMapper.selectRecommendedPostsByTags(
                        tagIds, userId, limit - recommendedPosts.size());
                
                // 合并推荐结果，避免重复
                for (Map<String, Object> post : tagRecommendedPosts) {
                    boolean isDuplicate = false;
                    for (Map<String, Object> existingPost : recommendedPosts) {
                        if (existingPost.get("id").equals(post.get("id"))) {
                            isDuplicate = true;
                            break;
                        }
                    }
                    if (!isDuplicate) {
                        recommendedPosts.add(post);
                        if (recommendedPosts.size() >= limit) {
                            break;
                        }
                    }
                }
            }
        }
        
        // 如果推荐数量仍然不足，补充热门帖子
        if (recommendedPosts.size() < limit) {
            List<Map<String, Object>> hotPosts = foodPostMapper.selectHotPostsExcludeUser(
                    userId, limit - recommendedPosts.size());
            
            // 合并推荐结果，避免重复
            for (Map<String, Object> post : hotPosts) {
                boolean isDuplicate = false;
                for (Map<String, Object> existingPost : recommendedPosts) {
                    if (existingPost.get("id").equals(post.get("id"))) {
                        isDuplicate = true;
                        break;
                    }
                }
                if (!isDuplicate) {
                    recommendedPosts.add(post);
                    if (recommendedPosts.size() >= limit) {
                        break;
                    }
                }
            }
        }
        
        return recommendedPosts;
    }

    @Override
    public List<Map<String, Object>> getRecommendedRestaurants(Long userId, int limit) {
        // 基于用户偏好的餐厅菜系，推荐相关餐厅
        List<Map<String, Object>> recommendedRestaurants = new ArrayList<>();
        
        // 获取用户偏好餐厅菜系
        List<Map<String, Object>> preferredCuisineTypes = dataAnalysisMapper.getUserPreferredCuisineTypes(userId);
        
        // 如果用户有偏好菜系，基于菜系推荐
        if (preferredCuisineTypes != null && !preferredCuisineTypes.isEmpty()) {
            // 从偏好菜系中获取前3个菜系
            List<String> cuisineTypes = new ArrayList<>();
            for (int i = 0; i < Math.min(3, preferredCuisineTypes.size()); i++) {
                cuisineTypes.add(preferredCuisineTypes.get(i).get("cuisine_type").toString());
            }
            
            // 基于菜系获取推荐餐厅
            if (!cuisineTypes.isEmpty()) {
                // 这里需要在RestaurantMapper中添加相应的方法
                recommendedRestaurants.addAll(restaurantMapper.selectRecommendedRestaurantsByCuisineTypes(
                        cuisineTypes, userId, limit));
            }
        }
        
        // 如果推荐数量不足，补充高评分餐厅
        if (recommendedRestaurants.size() < limit) {
            List<Map<String, Object>> highRatedRestaurants = restaurantMapper.selectHighRatedRestaurantsExcludeUser(
                    userId, limit - recommendedRestaurants.size());
            
            // 合并推荐结果，避免重复
            for (Map<String, Object> restaurant : highRatedRestaurants) {
                boolean isDuplicate = false;
                for (Map<String, Object> existingRestaurant : recommendedRestaurants) {
                    if (existingRestaurant.get("id").equals(restaurant.get("id"))) {
                        isDuplicate = true;
                        break;
                    }
                }
                if (!isDuplicate) {
                    recommendedRestaurants.add(restaurant);
                    if (recommendedRestaurants.size() >= limit) {
                        break;
                    }
                }
            }
        }
        
        return recommendedRestaurants;
    }

    @Override
    public List<Map<String, Object>> getHotFoodRanking(int limit) {
        // 获取热门美食排行榜
        return foodPostMapper.selectHotPostsRanking(limit);
    }

    @Override
    public List<Map<String, Object>> getHotRestaurantRanking(int limit) {
        // 获取热门餐厅排行榜
        return restaurantMapper.selectHotRestaurantsRanking(limit);
    }
} 